﻿
using Dt261.db;
using Dt261.Model;
using Dt261.Views;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Panuon.UI.Silver;
using Panuon.UI.Silver.Core;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using DMSkin.Core;
using System.Threading;
using Dt261.jsonmodel;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using Newtonsoft.Json;
using System.Collections;
using System.Windows.Media;

namespace Dt261.ViewModel
{
    class UserPageViewModel: GalaSoft.MvvmLight.ViewModelBase
    {

        System.Timers.Timer t;

        private string searchText=string.Empty;
        private string name = "暂无成员";
        MemberInfoDb db;
        UserDb userDB;
        PureToneResultDb resultDB;

      

        SpeechResultDb speechResultDB;
        private ObservableCollection<PureToneResult> allResults;
        public ObservableCollection<PureToneResult> AllResults { get => allResults; set { Set(ref allResults, value); } }
        PureToneResult selectPureToneResult;

        public delegate void selectPureToneResultchanged(List<ResultDataSet> DataSets, int needLink = 0);// /*Dictionary<int, TestItem> list*/, bool isright, int mmtype = 0, int needLink = 0);
        //定义一个事件
        public event selectPureToneResultchanged SelectPureToneResultEvent;

        public delegate void selectMemberchanged();
        //定义一个事件
        public event selectMemberchanged SelectMemberChangeEvent;

        private ObservableCollection<MemberInfo> allMembers;
        private MemberInfo selectMember;

        public ObservableCollection<MemberInfo> AllMembers{ get => allMembers; set { Set(ref allMembers, value); } }



        SpeechResultItem selectSpeechResult;


        private ObservableCollection<SpeechResultItem> allSpeechResults;
        public ObservableCollection<SpeechResultItem> AllSpeechResults { get => allSpeechResults; set { Set(ref allSpeechResults, value); } }
        public SpeechResultItem SelectSpeechResult { get => selectSpeechResult; set { selectSpeechResult = value; RaisePropertyChanged(); } }


        public string IsHasMember { get => selectMember != null ? "Visible" : "Hidden"; set
            {
               
                RaisePropertyChanged();
            }
        }
  

        public string Name
        { 
            get => name; set
            {
                name = value != null ? value : "暂无成员";
                RaisePropertyChanged();
            }
        }
        public PureToneResult SelectPureToneResult
        {
            get => selectPureToneResult;
            set
            {
                
                selectPureToneResult = value;
                if(SelectPureToneResultEvent != null)
                {
                    //SelectPureToneResultEvent(null, true);
                    //SelectPureToneResultEvent(null, false);
                    //SelectPureToneResultEvent(null, true, 1);
                    //SelectPureToneResultEvent(null, false, 1);
                    if (value != null)
                    {

                        resultDB.GetChildrenByUid(value);
                        RaisePropertyChanged();
                        selectPureToneResultIsChange();
                    }

                }
   


            }
        }



        public void selectPureToneResultIsChange()
        {
            //    foreach(ResultDataSet dataset in SelectPureToneResult.DataSets)
            //    {
            //        Dictionary<int, TestItem> dict = new Dictionary<int, TestItem>();
            //        foreach(ResultEntry entry in dataset.Entrys)
            //        {
            //            TestItem item = new TestItem();
            //            item.Hz = entry.ValueX;
            //            item.Db = entry.ValueY;
            //            if (entry.PointState == 1)
            //            {
            //                item.Mask = true;
            //                item.MaskV = 0;
            //                //...
            //            }
            //            else
            //            {
            //                item.Mask = false;
            //                item.MaskV = 0;
            //                //...
            //            }

            //            if (entry.IsUserResp == 0)
            //                item.IsUserResp = false;
            //            else
            //                item.IsUserResp = true;
            //            item.abc = entry.Mmtype;
            //            item.MarkType = entry.MarkType;
            //            dict.Add(item.Hz, item);

            //                //List<TestItem> listChild = this.rightResult.ToList();
            //                //listChild.Sort(delegate (TestItem p1, TestItem p2) { return Comparer<int>.Default.Compare(p1.Hz, p2.Hz); });
            //                ////List列表转为ObservableCollection集合
            //                //this.rightResult = new ObservableCollection<TestItem>(listChild);
            //         }
            //        //this.IsRightEar 
            //        SelectPureToneResultEvent(dict, dataset.IsRight == 1,dataset.HeadsetMode, SelectPureToneResult.State);

            //    }
            //
            SelectPureToneResultEvent(SelectPureToneResult.DataSets, SelectPureToneResult.State);

        }

        public void SelectResult()
        {
            //getListenTests();
            // getSpeechInfo();
            //if (AllResults != null)
            //{
            //    Task t1 = new Task(new Action(SelectPureToneResult = AllResults.FirstOrDefault();));

            if (SelectMember == null)
                return;
            //}
            AllResults = new ObservableCollection<PureToneResult>(resultDB.GetResultsByMemberId(SelectMember.Uid));
            SelectPureToneResult = AllResults.FirstOrDefault();

            getSpeechInfo();
            SelectSpeechResult = AllSpeechResults.FirstOrDefault();

        }
        public MemberInfo SelectMember { get => selectMember;
            set {
                if (SelectMemberChangeEvent != null)
                    SelectMemberChangeEvent();
                if (value != null)
                {
                    selectMember = value;
                   
                    DeleteMemberCommand.RaiseCanExecuteChanged();
                    EditMemberCommand.RaiseCanExecuteChanged();
                    AllResults = new ObservableCollection<PureToneResult>(resultDB.GetResultsByMemberId(value.Uid));
                    SelectPureToneResult = AllResults.FirstOrDefault();
                   
                   


                }
                else
                {
                    selectMember = null;
                    AllResults = new ObservableCollection<PureToneResult>();
                    SelectPureToneResult = null;
                }
                Name = selectMember==null? "暂无成员" : selectMember.Name;
                IsHasMember = selectMember != null ? "Visible" : "Hidden";
                RaisePropertyChanged();

            }
        }


        public UserPageViewModel()
        {

           

            AddMemberCommand = new RelayCommand(AddMember);
            EditMemberCommand = new RelayCommand(EditMember);
            DeleteMemberCommand = new RelayCommand(DeleteMember);
            SearchMemberCommand = new RelayCommand(SearchMember);


            db = new MemberInfoDb(dbconfig.DatabasePath);
            userDB = new UserDb(dbconfig.DatabasePath);
            resultDB = new PureToneResultDb(dbconfig.DatabasePath);
            //dataSetDB = new ResultDataSetDb(dbconfig.DatabasePath);
            //entryDB = new ResultEntryDb(dbconfig.DatabasePath);

           

            speechResultDB = new SpeechResultDb(dbconfig.DatabaseFilename);
            //getInitInfo();

            //Task t1 = new Task(new Action(getInitInfo));
            //t1.Start();
            // getInitInfo();
            DMSkin.Core.Broadcast.RegisterBroadcast<string>("NavigationBack", (obj) =>
            {
                getInitInfo();
                getSpeechInfo();
            });
            DMSkin.Core.Broadcast.RegisterBroadcast<string>("NavigationBack2", (obj) =>
            {
                getInitInfo();
                getSpeechInfo();
            });


     
            t = new System.Timers.Timer(100000);//实例化Timer类，设置间隔时间为10000毫秒；
            t.Elapsed += new System.Timers.ElapsedEventHandler(Upload);//到达时间的时候执行事件；
            t.AutoReset = true;//设置是执行一次（false）还是一直执行(true)；
            t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件；
            t.Start(); //启动定时器
                       //上面初始化代码可以写到构造函数中
        }

        private void Upload(object source, System.Timers.ElapsedEventArgs e)
        {
            t.Stop(); //先关闭定时器
                      // MessageBox.Show("OK!");

            //上传用户和记录

            if(AllMembers != null && AllMembers.Count > 0 )
            { 
            foreach (MemberInfo m in AllMembers)
            {
                if(m.IsUpload != 1)
                {
                    {


                        Console.WriteLine("上传用户"+m.Uid);

                        //得改造一下m

                        Dictionary<string, Object> dict = new Dictionary<string, Object>();

                        //var json = JsonConvert.SerializeObject(m);
                        //var dictionary = JsonConvert.DeserializeObject<Dictionary<string, Object>>(json);



                        dict.Add("id", m.Uid);
                        dict.Add("address", m.Address);
                            //dict.Add("memberId", m.Uid);
                           dict.Add("age",  m.Age);
                        //    dict.Add("age", DateTime.Now.Year - m.Birthday.Year);
                        
                        dict.Add("audiphone", m.DeafAidLeftModel);
                        dict.Add("audiphoneRight", m.DeafAidRightModel);
                        dict.Add("auricle", m.DeviceWT);
                        long jan1st1970ms = new DateTime(1970, 1, 1, 0, 0, 0).Ticks;//, DateTimeKind.Local
                                                                                                  // dict.Add("birthday", (m.Birthday.Ticks - jan1st1970ms) / 10000);
                                                                                                  //dict.Add("birthday", (m.Birthday.Ticks - jan1st1970ms) / 10000);//+ DateTime.Now.AddYears(0-m.Age)
                                                                                                  //dict.Add("birthday",""+ (DateTime.Now.Year-m.Age)+"-"+ DateTime.Now.Month.ToString("D2") + "-" + DateTime.Now.Day.ToString("D2"));

                            string s = m.Birthday.ToString("u");
                            string s2 = s.Substring(0,s.Length-1);
                            dict.Add("birthday", s2);


                                                       dict.Add("creatTime", (m.CreateTime.ToUniversalTime().Ticks - jan1st1970ms) / 10000);

                        dict.Add("deafAidThreshold", m.DeafAidThreshold);
                        dict.Add("identity", m.IdCard);
                            dict.Add("modifyDate", 0);// (m.CreateTime.Ticks - jan1st1970ms) / 10000);


                        dict.Add("name", m.Name);
                        dict.Add("phone", m.Phone);

                        dict.Add("program", m.Note);
                        dict.Add("remarks", m.Mark);
                        dict.Add("state", m.State);

                        dict.Add("soundField", m.SoundField);
                        dict.Add("strength", m.Strength);
                        dict.Add("tinnitus", m.Tinnitus);
                        dict.Add("volume", m.DeafAidVolume);
                        dict.Add("zipCode", m.ZipCode);
                        dict.Add("sex", m.Gender);

                        if (GlobalData.LoginNetUser != null)
                        {
                            dict.Add("ordinaryUserId", GlobalData.LoginNetUser.id);
                        }
                        

                        Object[] array = new Object[1];
                        array[0] = dict;


                        var http = Http.SharedHttp();
                        StringContent jsonContent = new StringContent(JsonConvert.SerializeObject(array), Encoding.UTF8, "application/json");

                        string result = http.GetJSonResponse(JsonConvert.SerializeObject(array), Http.HOST + "tlyht/formal/tlj/uploadMemberList", "post");



                        if (result != null)
                        {
                            Console.WriteLine(result);

                            JObject o = (JObject)JsonConvert.DeserializeObject(result);

                            if (null == Http.errorWithJsonObject(o))
                                {
                                    m.IsUpload = 1;
                                   //m.ModifyDate = o["Persons"].ToString()
                                }
                               
                            db.UpdateMember(m);

                            uploadTest(m);

                        }



                    }


                }
                else
                {
                    uploadTest( m);
                }
                
            }

            }
            t.Start(); //执行完毕后再开启器
        }


        private void uploadTest(MemberInfo m)
        {

            IList<PureToneResult> list = resultDB.GetResultsByMemberId(m.Uid);

            if (list.Count <= 0) return;

            foreach (PureToneResult r in list)
            {

                if (r.IsUpload != 1)
                {
                    Console.WriteLine("上传记录" + r.Uid);
                    resultDB.GetChildrenByUid(r);
                    ArrayList testRecord = new ArrayList();

                    foreach (ResultDataSet set in r.DataSets)
                    {
                        testRecord.Add(set.getResultDictory());
                    }

                    {
                        var http = Http.SharedHttp();




                        Dictionary<string, Object> dict2 = new Dictionary<string, Object>();

                        dict2.Add("id", r.Uid);
                        if (r.DeviceWT != null)
                            dict2.Add("mac", r.DeviceWT);
                        dict2.Add("status", 0);
                        dict2.Add("equipmentType", 0);
                        dict2.Add("memberId", m.Uid);
                        dict2.Add("noiseVal", 0);
                         long jan1st1970ms = new DateTime(1970, 1, 1, 0, 0, 0).Ticks;//, DateTimeKind.Local
                        dict2.Add("birthday", (m.Birthday.Ticks - jan1st1970ms) / 10000);
                        dict2.Add("modifyDate", 0);// (r.CreateTime.Ticks - jan1st1970ms) / 10000);
                        dict2.Add("createDate", (r.CreateTime.ToUniversalTime().Ticks - jan1st1970ms) / 10000);
                        dict2.Add("testRecord", testRecord);
                        //得改造一下m
                        //NSDictionary* dict = @{
                        //    @"equipmentType":@0,
                        //                   @"id":result.id,
                        //                   @"mac":@"",
                        //                   //@"birthday":@((long long)([member.birthday timeIntervalSince1970])*1000),
                        //                   @"memberId":result.member.id,
                        //                   @"noiseVal":@0,
                        //                   @"modifyDate":result.modifyDate,
                        //                   @"status":result.state,
                        //                   @"testRecord":testRecords,
                        //                   };
                        Dictionary<string, Object>[] array2 = new Dictionary<string, Object>[1];
                        array2[0] = dict2;

                        //StringContent jsonContent = new StringContent(JsonConvert.SerializeObject(array), Encoding.UTF8, "application/json");



                        string res = http.GetJSonResponse(JsonConvert.SerializeObject(array2), Http.HOST + "tlyht/formal/tlj/uploadAudiometer", "post");



                        if (res != null)
                        {
                            Console.WriteLine(res);

                            JObject oo = (JObject)JsonConvert.DeserializeObject(res);

                            if (null == Http.errorWithJsonObject(oo))
                            {
                                r.IsUpload = 1;
                                resultDB.UpdatePureToneResult(r);
                            }




                        }



                    }
                }

            }
        }

        public RelayCommand AddMemberCommand { get; set; }
        public RelayCommand DeleteMemberCommand { get; set; }
        public RelayCommand EditMemberCommand { get; set; }
        public RelayCommand SearchMemberCommand { get; set; }
        public string SearchText { get => searchText; set { searchText = value;RaisePropertyChanged(); } }


        #region Methods

        public void getInitInfoByPostHost()
        {
            var http = Http.SharedHttp();
            //http.Request.Accept = HttpContentTypes.ApplicationJson;
            //http.Request.ContentType = HttpContentTypes.ApplicationXWwwFormUrlEncoded;

            //var content = new FormUrlEncodedContent(new[]
            //{
            //    new KeyValuePair<string, string>("id", GlobalData.LoginNetUser.id)

            //});

            try {

            string result = http.GetResponse(null, Http.PostHost + "tlyht/user/person/findAllTo", "post");



            if (result != null)
            {
                Console.WriteLine(result);

                JObject o = (JObject)JsonConvert.DeserializeObject(result);

                if (null == Http.errorWithJsonObject(o))
                {

                    IList<MemberNetInfo> listOrder = new List<MemberNetInfo>();


                    listOrder = JsonConvert.DeserializeObject<IList<MemberNetInfo>>(o["Persons"].ToString());

                    if (listOrder.Count <= 0)

                    {
                        // Log4.WriteLog("没有获取到可以写入的数据记录");
                        return;
                    }

                    if(GlobalData.IsDeleteLocal == true)
                    {
                        IList<MemberInfo> list =  db.GetMembersByUserId(GlobalData.LoginUser.Uid);

                            foreach (MemberInfo m in list)
                            {
                                db.DeleteMemberInfo(m);
                            }
                 
                    }


                    for (int i = 0; i < listOrder.Count(); i++)
                    {

                        //循环解析每一个实体
                        MemberNetInfo info = listOrder[i];

                        MemberInfo m = db.GetOneMemberByUid(info.id);

                        if (m == null)
                            m = new MemberInfo();

                        m.Uid = info.id;
                        m.UserId = info.ordinaryUserId;
                        m.Name = info.name;
                        m.Phone = info.phone;
                        m.Note = info.relationship;
                        m.Mark = info.remarks;
                        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));//当地时区
                        var time = startTime.AddSeconds(Convert.ToDouble(info.birthday) / 1000);
                        m.Birthday = time;
                        m.Age = Convert.ToInt32((DateTime.Now.Year - time.Year));
                        //Convert.ToInt32(info.age);
                        m.Gender = info.sex.Equals("0") ? 1 : 0;
                        //m.IdCard = IdCard;
                        //m.Insurance = Insurance;
                        m.Address = info.address;
                        m.ZipCode = info.zipcode;
                        //m.AllergyHistory = AllergyHistory;
                        //m.History = History;
                        //m.DeafAidRoutine = DeafAidRoutine;
                        //m.DeafAidThreshold = DeafAidThreshold;
                        //m.SoundField = SoundField;
                        //m.Tinnitus = Tinnitus;
                        //m.Strength = Strength;
                        //m.DeafAidLeftModel = DeafAidLeftModel;
                        //m.DeafAidRightModel = DeafAidRightModel;
                        //m.DeviceWT = DeviceWT;
                        //m.Note = Chengxu;
                        //m.DeafAidVolume = DeafAidVolume;
                        //m.IdCard = IdCard;
                        db.UpdateMember(m);

                    }

                }
                else
                {
                    //this.Report = Http.errorWithJsonObject(o) + ",请重试!";
                }

                getInitInfo();
            }
            else
            {
                getInitInfo();
            }
                //var response = http.Post(, dict, HttpContentTypes.ApplicationXWwwFormUrlEncoded);

            }catch
            {
                Notice.Show("从配置的对接接口未获取到数据", "提示",2, MessageBoxIcon.Warning);
                getInitInfo();
            }




        }
        public void getInitInfoByNetUser()
        {
            var http = Http.SharedHttp();
            //http.Request.Accept = HttpContentTypes.ApplicationJson;
            //http.Request.ContentType = HttpContentTypes.ApplicationXWwwFormUrlEncoded;

            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("id", GlobalData.LoginNetUser.id)

            });


            string result = http.GetResponse(content, Http.HOST + "tlyht/user/person/findAllTo", "post");



            if (result != null)
            {
                Console.WriteLine(result);

                JObject o = (JObject)JsonConvert.DeserializeObject(result);

                if (null == Http.errorWithJsonObject(o))
                {

                    IList<MemberNetInfo> listOrder = new List<MemberNetInfo>();


                    listOrder = JsonConvert.DeserializeObject<IList<MemberNetInfo>>(o["Persons"].ToString());

                    if (listOrder.Count <= 0)

                    {
                        // Log4.WriteLog("没有获取到可以写入的数据记录");
                        return;
                    }
                    for (int i = 0; i < listOrder.Count(); i++)
                    {

                        //循环解析每一个实体
                        MemberNetInfo info = listOrder[i];

                        MemberInfo m = db.GetOneMemberByUid(info.id);

                        if (m == null)
                            m = new MemberInfo();

                        m.Uid = info.id;
                        m.UserId = info.ordinaryUserId;
                        m.Name = info.name;
                        m.Phone = info.phone;
                        m.Note = info.relationship;
                        m.Mark = info.remarks;
                        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));//当地时区
                        var time = startTime.AddSeconds(Convert.ToDouble(info.birthday) / 1000);
                        m.Birthday = time;
                        m.Age = Convert.ToInt32((DateTime.Now.Year - time.Year));
                        //Convert.ToInt32(info.age);
                        m.Gender = info.sex.Equals("0") ? 1 : 0;
                        //m.IdCard = IdCard;
                        //m.Insurance = Insurance;
                        m.Address = info.address;
                        m.ZipCode = info.zipcode;
                        //m.AllergyHistory = AllergyHistory;
                        //m.History = History;
                        //m.DeafAidRoutine = DeafAidRoutine;
                        //m.DeafAidThreshold = DeafAidThreshold;
                        //m.SoundField = SoundField;
                        //m.Tinnitus = Tinnitus;
                        //m.Strength = Strength;
                        //m.DeafAidLeftModel = DeafAidLeftModel;
                        //m.DeafAidRightModel = DeafAidRightModel;
                        //m.DeviceWT = DeviceWT;
                        //m.Note = Chengxu;
                        //m.DeafAidVolume = DeafAidVolume;
                        //m.IdCard = IdCard;
                        db.UpdateMember(m);

                    }

                }
                else
                {
                    //this.Report = Http.errorWithJsonObject(o) + ",请重试!";
                }

                getInitInfo();
            }
            //var response = http.Post(, dict, HttpContentTypes.ApplicationXWwwFormUrlEncoded);






        }

        public void getInitInfo()
        {
            string selectUid = null;
            string selectResultUid = null;

            if (SelectMember != null)
            {
                //index = AllMembers.IndexOf(SelectMember);
                selectUid = SelectMember.Uid;
            }

            if (SelectPureToneResult != null)
            {
                //index = AllMembers.IndexOf(SelectMember);
                selectResultUid = SelectPureToneResult.Uid;
            }


            AllMembers = new ObservableCollection<MemberInfo>(db.GetMembersByUserId(GlobalData.LoginUser.Uid));

            //if (SelectMember == null)
            //    SelectMember = AllMembers.FirstOrDefault();
            if (selectUid != null)//index > -1 && index < AllMembers.Count() && AllMembers.Contains(SelectMember) == false)
            {
                foreach (MemberInfo m in AllMembers)
                {
                    if (m.Uid == selectUid)
                        SelectMember = m;// AllMembers[index];
                }
                if (SelectMember == null)
                    SelectMember = AllMembers.FirstOrDefault();
            }
            else
            {
                SelectMember = AllMembers.FirstOrDefault();
            }

            if (SelectMember != null)
            {
                AllResults = new ObservableCollection<PureToneResult>(resultDB.GetResultsByMemberId(SelectMember.Uid));

                if (selectResultUid != null)//index > -1 && index < AllMembers.Count() && AllMembers.Contains(SelectMember) == false)
                {
                    foreach (PureToneResult m in AllResults)
                    {
                        if (m.Uid == selectResultUid)
                            SelectPureToneResult = m;// AllMembers[index];
                    }
                    if (SelectPureToneResult == null)
                        SelectPureToneResult = AllResults.FirstOrDefault();
                }
                else
                {
                    SelectPureToneResult = AllResults.FirstOrDefault();
                }
                
            }
            
}

        public void AddMember()
        {
            //需要跳转页面

            DMSkin.Core.Broadcast.PushBroadcast("Navigation", new UserInfoPage());
            // db.AddMember(new Model.User() { Uid = (new Random(111)).ToString() });
            //MemberInfo m = new MemberInfo();
            //m.Name = (new Random()).Next(999).ToString();
            //m.Uid = System.Guid.NewGuid().ToString("N");
            //m.UserId = userDB.LastUser().Uid;

            //db.AddMember(m);


            //AllMembers = new ObservableCollection<MemberInfo>(db.GetMembers());

            var _mainWindow = Application.Current.Windows
            .Cast<Window>()
            .FirstOrDefault(window => window is MainWindow) as MainWindow;


            MainWindowViewModel mainmodel = _mainWindow.DataContext as MainWindowViewModel;

            mainmodel.SendModel.SendData = "121212121212";
            mainmodel.SendAsync().GetAwaiter().OnCompleted(() => {
                mainmodel.DepictInfo = string.Format(mainmodel.CultureInfos, "fasongchengg");
            });


        }

        public void DeleteMember()
        {
            //if (DialogService.Confirm("Really want to delete this friend?"))
            var result = MessageBoxX.Show("确认删除已选测试成员？", "提醒", Application.Current.MainWindow, MessageBoxButton.YesNo, new MessageBoxXConfigurations()
            {
                MessageBoxStyle = MessageBoxStyle.Modern,
                MessageBoxIcon = MessageBoxIcon.Warning,
                ButtonBrush = "#F1C825".ToColor().ToBrush(),
            });

            if(result == MessageBoxResult.Yes)
            {
               
                db.DeleteMemberInfo(SelectMember);
                AllMembers.Remove(SelectMember);

                SelectMember = AllMembers.Count() > 0 ? AllMembers[0] : null;
                // DialogService.ShowMessage("Delete friend successfully");
            }
        }

        public void EditMember()
        {
            if(SelectMember == null)
            {
                var result = MessageBoxX.Show("请先添加测试成员", "提醒", Application.Current.MainWindow, MessageBoxButton.OK, new MessageBoxXConfigurations()
                {
                    MessageBoxStyle = MessageBoxStyle.Modern,
                    MessageBoxIcon = MessageBoxIcon.Warning,
                    ButtonBrush = "#F1C825".ToColor().ToBrush(),
                });

            //    if (result == MessageBoxResult.Yes)
            //    {

            //        DMSkin.Core.Broadcast.PushBroadcast("Navigation", new UserInfoPage(selectMember));
            //        // DialogService.ShowMessage("Delete friend successfully");
            //    }
            }
            //var result = EditWindowController.ShowDialog(new OpenEditWindowArgs { Type = ActionType.Edit, Friend = SelectedFriend });
           // if (result.HasValue && result.Value)
           else
            {
                DMSkin.Core.Broadcast.PushBroadcast("Navigation", new UserInfoPage(selectMember));



                //// Remember user's selection
                //int index = AllMembers.IndexOf(selectMember);
                //AllMembers = new ObservableCollection<MemberInfo>(db.GetMembers());

                //// re-selected the original item
                //SelectMember = AllMembers[index];
            }
        }

     
        private void SearchMember()
        {
            //var result = EditWindowController.ShowDialog(new OpenEditWindowArgs { Type = ActionType.Edit, Friend = SelectedFriend });
            // if (result.HasValue && result.Value)
            {
                // Remember user's selection
                //int index = AllMembers.IndexOf(selectMember);
                AllMembers = new ObservableCollection<MemberInfo>(db.SearchMemberInfo(GlobalData.LoginUser.Uid,SearchText));
                if(AllMembers.Count()>0)
                {
                    // re-selected the original item
                    SelectMember = AllMembers[0];
                }
 
            }
        }

        public void deleteTestResultByUid(string uid)
        {
        
            resultDB.DeletePureToneResultByUid(uid);
            AllResults = new ObservableCollection<PureToneResult>(resultDB.GetResultsByMemberId(SelectMember.Uid));
            SelectPureToneResult =  AllResults.Count() > 0 ? AllResults[0] : null;
        }


        public void deleteSpeechTestResult(SpeechResultItem c)
        {

            string uid = c.id;
            speechResultDB.DeleteSpeechResult(c);
            getSpeechInfo();
           // selectSpeechResult = 

            //var response = http.Post(, dict, HttpContentTypes.ApplicationXWwwFormUrlEncoded);


        }


        public void getSpeechInfo()
        {
            if (SelectMember != null && GlobalData.LoginUser != null)
            {

                IList<SpeechResultItem> listOrder =  speechResultDB.GetSpeechItemsByPersonId(SelectMember.Uid);

      

                if (listOrder.Count > 0)

                {
                    AllSpeechResults = new ObservableCollection<SpeechResultItem>(listOrder);
                    // Log4.WriteLog("没有获取到可以写入的数据记录");

                }
                else
                {
                    AllSpeechResults = new ObservableCollection<SpeechResultItem>();
                }

                

            }
        }
        #endregion Methods

    }
}
